package org.dtrd.modules.doctor.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.util.DateUtils;
import org.dtrd.modules.doctor.entity.bean.DoctorTeam;
import org.dtrd.modules.doctor.entity.bean.TeamDoctorInfo;
import org.dtrd.modules.doctor.entity.bean.TeamInfo;
import org.dtrd.modules.doctor.entity.po.DtrdEntRdDoctor;
import org.dtrd.modules.doctor.entity.po.DtrdEntRdDoctorTeam;
import org.dtrd.modules.doctor.entity.po.DtrdRlDoctorTeamDoctor;
import org.dtrd.modules.doctor.entity.request.SetTeamDoctorRequest;
import org.dtrd.modules.doctor.mapper.DtrdRlDoctorTeamDoctorMapper;
import org.dtrd.modules.doctor.service.IDtrdEntRdDoctorService;
import org.dtrd.modules.doctor.service.IDtrdEntRdDoctorTeamService;
import org.dtrd.modules.doctor.service.IDtrdRlDoctorTeamDoctorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 医生团队和医生的关系表 服务实现类
 * </p>
 *
 * @author QR
 * @since 2021-11-30 16:48:38
 */
@Slf4j
@Service
@DS("multi-datasource1")
public class DtrdRlDoctorTeamDoctorServiceImpl extends ServiceImpl<DtrdRlDoctorTeamDoctorMapper, DtrdRlDoctorTeamDoctor> implements IDtrdRlDoctorTeamDoctorService {

    @Autowired
    private IDtrdEntRdDoctorTeamService doctorTeamService;
    @Autowired
    private IDtrdEntRdDoctorService doctorService;

    @Override
    public boolean saveDoctorTeamRelation(SetTeamDoctorRequest request) {
        DtrdEntRdDoctor doctor = doctorService.getOrCreateDoctor(request.getDoctorName(), request.getDoctorPhone(), request.getDoctorType());
        Integer managerId = doctorTeamService.getManagerId(request.getTeamId());
        if (managerId != null) {
            return saveDoctorTeamRelation(managerId, doctor.getDataId());
        }
        return false;
    }

    @Override
    public boolean saveDoctorTeamRelation(Integer doctorId, Integer newDoctorId) {
        DtrdEntRdDoctorTeam team = doctorTeamService.getDoctorTeamByDoctorId(doctorId);
        if (team != null) {
            Integer teamId = team.getDataId();
            LambdaQueryWrapper<DtrdRlDoctorTeamDoctor> wrapper = Wrappers.lambdaQuery(DtrdRlDoctorTeamDoctor.class)
                    .eq(DtrdRlDoctorTeamDoctor::getTeamId, teamId)
                    .eq(DtrdRlDoctorTeamDoctor::getManageDoctorId, doctorId)
                    .eq(DtrdRlDoctorTeamDoctor::getDoctorId, newDoctorId);
            DtrdRlDoctorTeamDoctor doctorTeamRl = new DtrdRlDoctorTeamDoctor(teamId, newDoctorId, doctorId);
            return saveOrUpdate(doctorTeamRl, wrapper);
        }
        return false;
    }

    @Override
    public boolean removeDoctorTeamRelation(Integer doctorId, Integer teamId) {
        LambdaQueryWrapper<DtrdRlDoctorTeamDoctor> queryWrapper = Wrappers.lambdaQuery(DtrdRlDoctorTeamDoctor.class)
                .eq(DtrdRlDoctorTeamDoctor::getTeamId, teamId)
                .eq(DtrdRlDoctorTeamDoctor::getDoctorId, doctorId);
        return remove(queryWrapper);
    }

    @Override
    public DoctorTeam getTeamDoctors(Integer doctorId) {
        // 获取团队管理者的医生信息
        DtrdEntRdDoctor doctor = doctorService.getById(doctorId);
        TeamDoctorInfo managerInfo = new TeamDoctorInfo().parseFromPo(doctor);
        // 获取团队创建时间
        DtrdEntRdDoctorTeam team = doctorTeamService.getDoctorTeamByDoctorId(doctorId);
        // 获取团队下的所有成员
        LambdaQueryWrapper<DtrdRlDoctorTeamDoctor> doctorQueryWrapper = Wrappers.lambdaQuery(DtrdRlDoctorTeamDoctor.class)
                .eq(DtrdRlDoctorTeamDoctor::getManageDoctorId, doctorId);
        List<DtrdRlDoctorTeamDoctor> relationList = this.list(doctorQueryWrapper);
        List<TeamDoctorInfo> dtoList = new ArrayList<>(relationList.size() + 1);
        if (CollectionUtil.isNotEmpty(relationList)) {
            dtoList = relationList.stream()
                    .map(relation -> {
                        Integer teamDoctorId = relation.getDoctorId();
                        DtrdEntRdDoctor teamDoctor = doctorService.getById(teamDoctorId);
                        return new TeamDoctorInfo().parseFromPo(teamDoctor);
                    })
                    .collect(Collectors.toList());
        }
        // 加上自己
        // 取消创建者  肖 2022-04-18 17:40:31
//        dtoList.add(managerInfo);
        // 按照医生身份倒序排序
        dtoList.sort((d1, d2) -> d2.getDoctorType() - d1.getDoctorType());
        // 设置返回对象
        DoctorTeam doctorTeam = new DoctorTeam();
        doctorTeam.setManager(managerInfo);
        doctorTeam.setTeamDoctors(dtoList);
        if (team != null) {
            doctorTeam.setTeamId(team.getDataId());
            doctorTeam.setTeamCreateTime(DateUtils.formatDate(team.getCreateTime(), DateUtils.date_sdf.get().toPattern()));
            doctorTeam.setTeamName(team.getName());
        }
        return doctorTeam;
    }

    @Override
    public List<TeamDoctorInfo> getTeamDoctorList(Integer doctorId) {
        DoctorTeam doctorTeam = getTeamDoctors(doctorId);
        log.info("DtrdRlDoctorTeamDoctorServiceImpl.getTeamDoctorList.[doctorId  = " + doctorId + ";  team=" + doctorTeam);
        if (doctorTeam != null) {
            List<TeamDoctorInfo> dtoList = new ArrayList<>(3);
            dtoList.add(doctorTeam.getManager());
            if (CollectionUtil.isNotEmpty(doctorTeam.getTeamDoctors())) {
                dtoList.addAll(doctorTeam.getTeamDoctors());
            }
            return dtoList;
        }
        return null;
    }

    @Override
    public List<TeamDoctorInfo> getTeamDoctorListV2(Integer doctorId) {
        List<Integer> doctorIdList = baseMapper.getTeamDoctorId(doctorId);
        if (CollectionUtil.isEmpty(doctorIdList)) {
            // 尚无团队
            return null;
        }
        List<DtrdEntRdDoctor> doctors = doctorService.getDoctorInfoByDoctorIds(doctorIdList);
        if (CollectionUtil.isNotEmpty(doctors)) {
            List<TeamDoctorInfo> dtoList = new ArrayList<>(doctors.size());
            doctors.stream().map(doctor -> new TeamDoctorInfo().parseFromPo(doctor)).forEach(dtoList::add);
            return dtoList;
        }
        return null;
    }

    @Override
    public List<Integer> getTeamDoctorIdList(Integer doctorId) {
        return baseMapper.getTeamDoctorId(doctorId);
    }

    @Override
    public TeamInfo getTeamInfo(Integer teamId) {
        DtrdEntRdDoctorTeam team = doctorTeamService.getById(teamId);
        return Optional.ofNullable(team).map(p -> {
            TeamInfo teamInfo = new TeamInfo().parseFromPo(p);
            teamInfo.setManagerName(doctorService.getDoctorName(p.getManageDoctorId()));
            return teamInfo;
        }).orElse(null);
    }

    @Override
    public boolean removeDoctorTeam(Integer teamId) {
        // 查询到管理者id
        DtrdEntRdDoctorTeam team = doctorTeamService.getById(teamId);
        Integer managerId = team.getManageDoctorId();
        // 删除团队
        boolean result = doctorTeamService.removeById(teamId);
        // 删除关系
        LambdaQueryWrapper<DtrdRlDoctorTeamDoctor> deleteCondition = Wrappers.lambdaQuery(DtrdRlDoctorTeamDoctor.class)
                .eq(DtrdRlDoctorTeamDoctor::getManageDoctorId, managerId)
                .eq(DtrdRlDoctorTeamDoctor::getTeamId, teamId);
        remove(deleteCondition);
        return result;
    }

    @Override
    public void removeDoctorTeamRelation(List<Integer> doctorIds) {
        baseMapper.removeDoctorTeamRelation(doctorIds);
    }

    @Override
    public Integer geTeamIdByDoctorId(Integer doctorId) {
        return baseMapper.geTeamIdByDoctorId(doctorId);
    }

    @Override
    public Integer getManageTeamId(Integer doctorId) {
        DtrdEntRdDoctorTeam doctorTeam = doctorTeamService.getDoctorTeamByDoctorId(doctorId);
        if (doctorTeam == null) {
            return geTeamIdByDoctorId(doctorId);
        }
        return doctorTeam.getDataId();
    }

    @Override
    public List<Integer> getTeamDoctorIdListByTeamId(Integer teamId) {
        return baseMapper.getTeamDoctorIdListByTeamId(teamId);
    }

    @Override
    public List<DtrdEntRdDoctorTeam> getTeamDoctorListByDoctorId(Integer doctorId) {
        List<Integer> teamId = baseMapper.getAllTeamIdByDoctorId(doctorId);
        log.info("teamId========"+teamId);
        if (CollectionUtil.isNotEmpty(teamId)) {
            LambdaQueryWrapper<DtrdEntRdDoctorTeam> queryWrapper = Wrappers.lambdaQuery(DtrdEntRdDoctorTeam.class)
                    .in(DtrdEntRdDoctorTeam::getDataId, teamId)
                    .eq(DtrdEntRdDoctorTeam::getIsDel, 0);
            List<DtrdEntRdDoctorTeam> doctorTeam = doctorTeamService.list(queryWrapper);
            return doctorTeam;
        } else {
            return null;
        }
    }
}
